package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class PermissionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
        //1.获取当前登录用户
        //Employee employee = (Employee) request.getSession().getAttribute("USER_IN_SESSION");
        Employee employee = UserContext.getCurrentUser();
        //2.判断是否超管
        if (employee.isAdmin()){
            //是,放行
            return true;
        }
            //不是,发送请求 > 3
        //3.获取当前要执行的处理方法,(被拦截的方法)
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //4.判断是否有贴自定义注解
        RequiredPermission annotation = handlerMethod.getMethodAnnotation(RequiredPermission.class);
            //是,就获取对应权限
            //不是,放行
            if (annotation == null){
                return true;
            }
        //5.获取方法的权限
        String expression = annotation.expression();
        //6.获取当前登录用户拥有的权限集合
        //List<String> list = (List<String>) request.getSession().getAttribute("EXPRESSION_IN_SESSION");
        List<String> list = UserContext.getExpression();
        //7.判断用户拥有的权限表达式集合中是否包含该方法的权限表达式
            if (list.contains(expression)){
                //包含,放行
                return true;
            }
            //不包含,不放行,跳转到错误页面
        if (!handlerMethod.hasMethodAnnotation(ResponseBody.class)){ //判断有没有贴ResponseBody注解
            //跳转页面
            request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp")
                    .forward(request,response);
        }else {
            //响应json数据
            JsonResult jsonResult = new JsonResult(false,"没有权限操作!");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(jsonResult));

        }
        return false;
    }
}
